import 'whatwg-fetch';

// 程序版本
export function getAppVersion() {
	return "2.1.3.1";
}

const token = '?access_token=82500370-c0df-11e5-b57f-57604e1441bf'
function isDebug() {
	return window.location.hostname === 'localhost';
}

function ajaxCloud(func, para, callback) {
	const CLOUD_URL = window.location.protocol + '//' + window.location.host + '/web_api/';
	fetch(CLOUD_URL + func + token, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify(para)
	}).then(function (response) {
		return response.json()
	}).then(function (body) {
		callback(body);
	}).catch(function (ex) {
		console.log("Ajax return ex:", ex);
		if (typeof func === 'function') {
			callback(ex);
		}
	})
}

// 获取设备的UUID
export function getUuid() {
	return getCookie('uuid_' + getWechatId());
}

/**
 * 获取设备的序列号
 */
export function getDeviceSn() {
	return getCookie('device_sn_' + getWechatId()) || '';
}

/**
 * 获取绑定设备的序列号
 */
export function getDeviceId() {
	let device_id = getCookie('device_id_' + getWechatId());
	if (device_id) {
		return parseInt(device_id, 10);
	}
	return 0;
}

/**
 * 微信开放的序列号
 */
export function getopenid() {
	if (isDebug()) {
		return 'o1rqj03mGi4NMt3X8Bo2XcbRSZhk';
	}
	return getCookie('openid_' + getWechatId());
}

export function getWechatId() {
	if (isDebug()) {
		return 11;
	}
	let wechat_id = getCookie('wechat_id');
	if (wechat_id) {
		return parseInt(wechat_id, 10);
	};
	return 0;
}


export function setDeviceSn(device_sn) {
	saveCookie('device_sn_' + getWechatId(), device_sn);
}

export function setDeviceId(device_id) {
	saveCookie('device_id_' + getWechatId(), device_id || '');
}

export function bindDevice(openid, device_id, nick_name, callback) {
	let user_data = {
		openid: openid,
		device_id: device_id,
		nick_name: nick_name,
	}
	ajaxCloud("bind_new_device", user_data, callback)
}

export function saveDeviceInfo(data) {
	const wechat_id = getWechatId();
	let isEqually = true;
	if (data) {
		isEqually = (wechat_id === parseInt(data.wechat_id,10));
		// 返回有数据,并且对应的微信公众号是一致的
		if (isEqually) {
			saveCookie('device_sn_' + wechat_id, data.device_sn || '');
			saveCookie('device_id_' + wechat_id, data.device_id || '');
			saveCookie('uuid_' + wechat_id, data.uuid || '');
			saveCookie('baidu_http_token_' + wechat_id, data.token || '');
			saveCookie('permission_group_id_' + wechat_id, data.permission_group_id || 0);
			return;
		}
	}
	// 没有发现数据,或者是不匹配公众号id 全部清空
	saveCookie('device_sn_' + wechat_id, '');
	saveCookie('device_id_' + wechat_id, 0);
	saveCookie('uuid_' + wechat_id, '');
	saveCookie('baidu_http_token_' + wechat_id, '');
	saveCookie('permission_group_id_' + wechat_id, 0);
}

// 用户权限
export function getPermissionGroupId() {
	const permission_group_id = getCookie('permission_group_id_' + getWechatId());
	if (permission_group_id) {
		return parseInt(permission_group_id, 10);
	}
	return -1;
}


/* 
* 读取特定Cookie的通用函数 
*/
function getCookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + "=");
		if (start !== -1) {
			start = start + name.length + 1;
			var end = document.cookie.indexOf(";", start);
			if (end === -1) {
				end = document.cookie.length;
			}
			return decodeURI(document.cookie.substring(start, end));
		} else {
			return ""
		}
	}
	return "";
}

/* 
* 设置Cookie的通用函数，其中name是必须的参数。其它为可选，故用条件语句判断。 
* 在设置Cookie时若不设置过期时间则该Cookie为临时的，仅当此次会话可用 
*/
function setcookie(name, value, expires, path, domain, secure) {
	var curcookie = name + "=" + encodeURI(value)
		+ ((expires) ? ";expires=" + expires.toGMTString() : "")
		+ ((path) ? ";path=" + path : "")
		+ ((domain) ? ";domain=" + domain : "")
		+ ((secure) ? ";secure" : "");
	document.cookie = curcookie;
}

// Cookie的写入 
export function saveCookie(name, value) {
	var now = new Date();
	var time = 24 * 60 * 60 * 1000;
	now.setDate(now.getDate() + time);
	setcookie(name, value, now, '/');
}

function getBaiduHttpToken() {
	return getCookie('baidu_http_token_' + getWechatId());
}

// 搜索音频
export function searchAudio(uuid, words, page, callback) {
	const post = {
		device_uuid: uuid,
		tags: localStorage.getItem("search_words"),
		words: words,
		page: page,
		size: 20,
		token: getBaiduHttpToken()
	}
	ajaxCloud("baidu/search_audio", post, callback)
}

// 搜索专辑
export function searchAlbum(uuid, words, page, callback) {
	const post = {
		device_uuid: uuid,
		tags: localStorage.getItem("search_words"),
		words: words,
		page: page,
		size: 20,
		token: getBaiduHttpToken()
	}
	ajaxCloud("baidu/search_album", post, callback)
}


/**
 * 获取单个专辑下的节日列表
 * @param {设备uuid} uuid 
 * @param {专辑id} albumid 
 * @param {个数} psize 
 * @param {分页标志} upid 
 * @param {*} callback 
 */
export function getTrackList(uuid, albumid, psize, upid, callback) {
	const post = {
		uuid: uuid,
		albumid: albumid,
		page: 1,
		psize: psize,
		upid: upid,
		token: getBaiduHttpToken()
	}
	ajaxCloud("baidu/get_track_list", post, callback)
}

export function getAlbumList(category_id, latest_id, callback) {
	let user_data = {
		category_id: category_id,
		uuid: getUuid(),
		latest_id: latest_id
	}
	ajaxCloud("album_list", user_data, callback)
}

// 分组数据展示分页(查询出设备拥有的分组权限)
export function getAlbumGroupById(album_group_id, latest_id, callback) {
	let user_data = {
		album_group_id:album_group_id, uuid:getUuid(), latest_id:latest_id
	}
	ajaxCloud("album_group_by_id", user_data, callback)
}

/**
 * 添加音频到收藏类别
 */
export function addAudio(audio_id,category_id, callback) {
	ajaxCloud("add_audio", {audio_id:audio_id,uuid:getUuid(),category_id:category_id}, callback)
}
//从我的收藏移除音频
export function removeAudio(audio_id,category_id, callback) {
	ajaxCloud("remove_audio", {audio_id:audio_id,category_id,uuid:getUuid()}, callback)
}

// 添加专辑到我的收藏
export function addAlbum(album_id,category_id, callback) {
	ajaxCloud("add_album", {album_id:album_id,category_id:category_id ,uuid:getUuid()}, callback)
}
// 移除收藏的专辑
export function removeAlbum(album_id, category_id,callback) {
	ajaxCloud("remove_album", {album_id:album_id,category_id:category_id,uuid:getUuid()}, callback)
}

// 收藏到我的最爱
export function like(audio_id, category_id,callback) {
	ajaxCloud("add_store_audio", {audio_id:audio_id, uuid:getUuid(),category_id:category_id}, callback)
}
// 取消我的最爱
export function unlike(audio_id,category_id,callback) {
	ajaxCloud("remove_store_audio", {audio_id:audio_id,category_id:category_id, uuid:getUuid()}, callback)
}


// 分页获取专辑下的音频列表
export function getAudiosByAlbum(album_id, latest_id, count,callback) {
	let user_data = {
		uuid:getUuid(), 
		album_id:album_id, 
		latest_id:latest_id,
		count:count
	}
	ajaxCloud("get_audios", user_data, callback)
}
export function getTicket(url, callback) {
	var user_data = {
		url: url,
		wechat_id: getWechatId()
	}
	ajaxCloud("wxjsticket", user_data, function (titcket) {
		callback(titcket)
	})
}

/**
 * 显示时长格式
 * @param {时长毫秒} millseconds 
 */
export function getShowDuration(millseconds) {
	const second = Math.floor(millseconds % 60)
	let minite = Math.floor(millseconds / 60)
	return `${minite}:${second >= 10 ? second : `0${second}`}`
}


// 获最爱的音频个数s
export function getFavoriteCount() {
	return new Promise(function(resolve,reject){
		ajaxCloud("favorite_count", {uuid:getUuid(),range: localStorage.getItem('category_range')}, function(result){
			resolve(result);
		})
	})
}

// 获取类别个数
export function getCategoryCount() {
	return new Promise(function(resolve,reject){
		ajaxCloud("category_count", {uuid:getUuid(),range: localStorage.getItem('category_range')}, function(result){
			resolve(result);
		})
	});
}


// 获取最爱音频列表
export function getFavoriteList(id) {
	return new Promise(function(resolve ,reject) {
		ajaxCloud("favorite_list", {uuid:getUuid(),id:id}, function(result) {
			resolve(result);
		})
	})
}



/**
 * 获取收藏类别下的音频
 * @param {*} category_id 
 * @param {*} latest_audio_id 
 */
export function getCategoryAudios(category_id,latest_id) {
	return new Promise(function(resolve, reject) {
		ajaxCloud("store_category_list", {uuid:getUuid(), category_id:category_id,latest_id:latest_id},function(result){
			resolve(result);
		});
	})

}

//=================设备以及用户信息请求操作接口
export function getMembers(callback) {
	ajaxCloud("get_bind_users", {device_sn:getDeviceSn()}, callback)
}

// 更新设备信息
export function updateDeviceInfo(user, callback) {
	let data = {
		device_id: getDeviceId(),
		nick_name: user.nick_name,
		brithday: user.brithday,
		gender: user.gender,
		avatar_url: user.avatar,
	}
	ajaxCloud('update_device_info', data, callback)
}

// 获取用户信息
export function getUserInfo(callback) {
	ajaxCloud("user_info", {device_sn:getDeviceSn()}, callback)
}


/**
 * 获取热门排行列表(专辑的播放率)
 */
export function getRankAlbums(callback) {
	const user_data = {
		uuid: getUuid(),
		range: localStorage.getItem('category_range')
	}
	ajaxCloud("rank_album", user_data, callback)
}

// 分页获取排行专辑列表
export function getRankAlbumPage(play_rate, callback) {
	const user_data = {
		uuid: getUuid(),
		play_rate: play_rate,
		range: localStorage.getItem('category_range')
	}
	ajaxCloud("rank_album_page", user_data, callback)
}


/**
 * 获取专辑信息
 */
export function getAlbumInfo(album_id, callback) {
	ajaxCloud("album_info", {album_id:album_id}, callback)
}

/**
 * 获取设备的序列号
 */
export function getBindDevice(callback) {
	let user_data = {
		openid: getopenid(),
		wechat_id: getWechatId()
	}
	ajaxCloud("get_bind_device", user_data, callback)
}



/**
 * 获取OTA最新版本检查是否需要升级
 */
export function getOtaNewVersion(device_id, callback) {
	ajaxCloud("get_ota_new_version", { device_id: device_id }, callback)
}

/**
 *  获取当前设备的OTA版本(用于循环检查)
 */
export function getDeviceOtaVersion(device_id, callback) {
	ajaxCloud("get_device_ota_version", { device_id: device_id }, callback)
}

/**
 * 更新当前设备OTA固件信息
 */
export function updateOtaVersion(version, callback) {
	let user_data = {
		version: version,
		device_id: getDeviceId()
	}
	ajaxCloud("update_device_version", user_data, callback)
}

/**
 * 通知服务端有新的固件上传，服务端发出版本通知
 */
export function upgradeNotification(deviceType, new_version, callback) {
	ajaxCloud("notify_upgrade", { device_type: deviceType, new_version: new_version }, callback)
}


/**
 * 生成声波音频，并返回音频在服务端的url
 */
export function getSoundWavesAudio(ssid, password, callback) {
	ajaxCloud("get_sound_waves", { ssid: ssid, password: password }, callback)
}

/**
 * 删除声波音频
 */
export function delSoundWavesAudio(file_name, callback) {
	if (file_name === '') {
		return
	}
	ajaxCloud("del_sound_waves", { file_name: file_name }, callback)
}

/**
 * 区分设备是否为ios系统
 */
export function isiOS() {
	// return /Android/i.test(navigator.userAgent);
	return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}


// 用户解绑
export function unBindDevice(deviceSn, openId, callback) {
	ajaxCloud("unbind", { device_sn: deviceSn, open_id: openId }, callback)
}

// 百度播放
export function playBaiduAudio(device_uuid, album_id, track_id, callback) {
	const post = {
		device_uuid: device_uuid,
		album_id: album_id,
		track_id: track_id,
		token: getBaiduHttpToken()
	}
	ajaxCloud("baidu/play_audio", post, callback)
}

/**
 * 获取百度音频播放列表
 */
export function getBaiduPlayList(device_uuid, callback) {
	ajaxCloud("baidu/play_list", { device_uuid: device_uuid, token: getBaiduHttpToken() }, callback)
}

/**
 *  播放控制
 */
export function playControl(device_uuid, action, callback) {
	ajaxCloud("baidu/play_control", { device_uuid: device_uuid, action: action, token: getBaiduHttpToken() }, callback)
}

/**
 * 设备一上线,绑定设备
 */
export function bindDeviceUuid(device_sn, callback) {
	ajaxCloud("baidu/bind_device_uuid", { device_sn: device_sn, token: getBaiduHttpToken() }, callback)
}

/**
 * 通过百度接口获取设备在线的状态
 */
export function getDeviceOnline(uuid) {
	return new Promise(function (resolve, reject) {
		const postData = {
			device_uuid: uuid,
			token: getBaiduHttpToken(),
			data: {
				type: 1
			}
		}
		ajaxCloud('baidu/control_device', postData, function (result) {
			if (result.errcode === 0) {
				return resolve(result.data);
			} else {
				console.error(result);
				return resolve({ code: -1 });
			}
		});
	});
}

// 设置最大音量
export function setMaxVolume(uuid, maxVolume, callback) {
	const postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken(),
		data: {
			type: 2,
			max_volume: maxVolume
		}
	}
	ajaxCloud('baidu/control_device', postData, function (result) {
		if (result.errcode === 0) {
			return callback(result.data);
		} else {
			console.error(result);
			return callback({ code: -1 });
		}
	});
}

/**
 * 设置播放模式
 * @param {设备的uuid} uuid 
 * @param {播放类型} playCircleType 
 * @param {*} callback 
 */
export function setPlayCircleType(uuid, playCircleType, callback) {
	const postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken(),
		data: {
			type: 3,
			play_circle_type: playCircleType
		}
	}
	ajaxCloud('baidu/control_device', postData, function (result) {
		if (result.errcode === 0) {
			return callback(result.data);
		} else {
			console.error(result);
			return callback({ code: -1 });
		}
	});
}

// 设置锁定模式
export function setLockMode(uuid, lockValue, callback) {
	const postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken(),
		data: {
			type: 4,
			is_lock: lockValue
		}
	}
	ajaxCloud('baidu/control_device', postData, function (result) {
		if (result.errcode === 0) {
			return callback(result.data);
		} else {
			console.error(result);
			return callback({ code: -1 });
		}
	});
}

// 设置休眠时间
export function setSleepTime(uuid, sleepTime, callback) {
	const postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken(),
		data: {
			type: 6,
			sleep_time: sleepTime
		}
	}
	ajaxCloud('baidu/control_device', postData, function (result) {
		if (result.errcode === 0) {
			return callback(result.data);
		} else {
			console.error(result);
			return callback({ code: -1 });
		}
	});
}

// 获取设备版本号
export function getDeviceNewVersion(uuid, callback) {
	let postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken()
	}
	ajaxCloud('baidu/get_new_version', postData, callback)
}

// 升级设备
export function upgradeDevice(uuid, packageId, strategyId, callback) {
	const postData = {
		package_id: packageId,
		device_uuid: uuid,
		strategy_id: strategyId,
		token: getBaiduHttpToken()
	}
	ajaxCloud('baidu/upgrade_device', postData, callback)
}

// 获取升级状态
export function checkUpgradeStatus(uuid, callback) {
	ajaxCloud('baidu/check_upgrade', { device_uuid: uuid, token: getBaiduHttpToken() }, callback)
}

/**
 * 数据转换
 */
export function convetAudios(audioList) {
	let list = []
	for (let index = 0; index < audioList.length; index++) {
		const item = audioList[index];
		let audio = {}
		audio.album_id = parseInt(item.album_id, 10)
		audio.album_name = item.album_name
		audio.name = item.track_title
		audio.audio_id = parseInt(item.track_id, 10)
		if (item.cover_url) {
			audio.img_url = item.cover_url.middle
		} else {
			audio.img_url = ''
		}
		audio.play_count = item.play_count
		audio.duration = item.duration

		list.push(audio)
	}
	return list
}

// 获取专辑中音频列表转换
export function convetAudiosByAlbum(audioList) {
	let list = [];
	for (let index = 0; index < audioList.length; index++) {
		const item = audioList[index];
		let audio = {};
		audio.album_id = parseInt(item.album_id, 10);
		audio.album_name = item.album_name;
		audio.name = item.name;
		audio.audio_id = parseInt(item.id, 10);
		if (item.cover_url) {
			audio.img_url = item.cover_url.middle;
		} else {
			audio.img_url = '';
		}
		audio.episode = item.episode;
		audio.play_count = item.play_count;
		audio.duration = item.duration;
		audio.track_num = item.track_num;

		list.push(audio);
	}
	return list;
}

export function convetAlbums(albumList) {
	let list = [];
	for (let index = 0; index < albumList.length; index++) {
		const item = albumList[index];
		let album = {};
		album.album_id = parseInt(item.album_id, 10);
		album.name = item.album_name;
		if (item.track_num) {
			album.count = item.track_num;
		} else {
			album.count = 0;
		}
		if (item.cover_url) {
			album.img_url = item.cover_url.middle;
		} else {
			album.img_url = '';
		}
		album.play_count = item.play_count;
		list.push(album);
	}
	return list;
}


export function getTrackInfo(uuid, track_id, callback) {
	const postData = {
		uuid: uuid,
		track_id: track_id,
		token: getBaiduHttpToken()
	};
	ajaxCloud('baidu/get_track', postData, callback);
}


export function mqttState(message) {
	let postData = {
		message: message
	};
	ajaxCloud('mqtt', postData, (data) => { });
}

/**
 * 分享设备
 */
export function shareQRCode(deviceSn, callback) {
	let postData = {
		device_sn: deviceSn
	};
	ajaxCloud('share_qrcode', postData, callback);
}


/**
 * 删除设备中的用户
 * @param {*} deleteUserOpenid 
 * @param {*} callback 
 */
export function removeDeviceUser(deleteUserOpenid, callback) {
	let post = {
		device_sn: getDeviceSn(),
		openid: deleteUserOpenid
	};
	ajaxCloud('remove_device_user', post, callback);
}

/**
 * 过滤专辑
 */
export function getPrimaryAlbumList() {
	return new Promise(function (resolve, reject) {
		ajaxCloud('primary_album_list', {uuid:getUuid()}, (data) => {
			console.log(data);
			if (data.errcode === 0) {
				return resolve(data.data);
			}
			return resolve([]);
		});
	})
}

/**
 * 过滤收费专辑
 */
export function isContrainAlbum(albumList, item) {
	if (!albumList || albumList.length === 0) {
		return true;
	}
	for (let index = 0; index < albumList.length; index++) {
		const album = albumList[index];
		if (album.album_id === item.album_id) {
			return false;
		}
	}
	return true;
}

// 获取设备的版本
export function getDeviceVersion(uuid, callback) {
	let postData = {
		device_uuid: uuid,
		token: getBaiduHttpToken()
	}
	ajaxCloud('baidu/get_version', postData, callback)
}

export function sleep(time) {
	return new Promise(function (reslove, rejct) {
		setTimeout(reslove, time);
	})
}

// 获取首页数据
export function getAlbumGroup() {
	let permission_group_id = -1;
	if (getUuid()) {
		permission_group_id = getPermissionGroupId();
	}
	const post = {
		uuid: getUuid(),
		album_group_template_id: localStorage.getItem('album_group_template_id'),
		permission_group_id: permission_group_id
	}
	return new Promise(function (resolve, reject) {
		ajaxCloud('get_album_group', post, function (result) {
			resolve(result);
		})
	})
}

export function setDocumentTitle(title) {
	document.title = title;
	if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
		var i = document.createElement('iframe');
		i.src = '/favicon.ico';
		i.style.display = 'none';
		i.onload = function () {
			setTimeout(function () {
				i.remove();
			}, 9)
		}
		document.body.appendChild(i);
	}
}

/**
 * 获取正在配网的设备信息
 */
export function getScanningDeviceSn() {
	return new Promise(function (resolve, reject) {
		ajaxCloud('get_device_sn', {}, function (result) {
			resolve(result);
		});
	});
}

/**
 * 自定义播放音频
 * @param {点播的类别} category_id 
 * @param {当前播放音频的上一个位置 } beforeAudioId
 */
export function customPlayAudio(category_id,beforeAudioId){
	return new Promise(function (resolve, reject) {
		ajaxCloud('baidu/custom_play', {uuid:getUuid(),token:getBaiduHttpToken(),category_id:category_id, audio_id:beforeAudioId}, function (result) {
			resolve(result);
		});
	});
}

/**
 * 通知设备播放模式
 * @param {当前播放音频} currentAudioId 
 */
export function sendModeToDevice(currentAudioId,categoryId){
	return new Promise(function(resolve,reject) {
		const post = {
			device_uuid: getUuid(),
			token: getBaiduHttpToken(),
			data: {
				type: 7,
				current_audio_id: currentAudioId,
				category_id:categoryId,
			}
		}
		ajaxCloud('baidu/control_device', post, function (result) {
			resolve(result);
		});
	})
}

/**
 * 清空我的最爱音频
 */
export function removeFavorite(){
	return new Promise(function(resolve, reject) {
		const post = {
			uuid:getUuid()
		}

		ajaxCloud('remove_favorite', post,function(result){
			resolve(result);
		})
	})
}

/**
 * 删除我的收藏类别
 * @param {收藏类别} category_id 
 */
export function removeStoreCategory(category_id) {
	return new Promise(function(resolve, reject) {
		const post = {
			uuid:getUuid(),
			category_id:category_id
		}
		ajaxCloud('remove_store_category', post,function(result){
			resolve(result);
		})
	})
}

/**
 * 
 * @param {类别} category_id 
 */
export function findCategoryAudioList(category_id){
	return new Promise(function(resolve, reject) {
		const post = {
			uuid:getUuid(),
			category_id:category_id
		}
		ajaxCloud('find_store_list', post,function(result){
			resolve(result);
		})
	})

}
















